package com.gardenguell.salad.ui.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.gardenguell.salad.R;
import com.gardenguell.salad.app.AppContext;
import com.gardenguell.salad.app.HandlerCenter;
import com.gardenguell.salad.data.cache.CacheService;
import com.gardenguell.salad.data.client.SaladClient;
import com.gardenguell.salad.data.model.BaseModel;
import com.gardenguell.salad.data.model.Unit;
import com.gardenguell.salad.data.volley.OnSuccessResponse;
import com.gardenguell.salad.ui.activity.BoxActivity;
import com.gardenguell.salad.ui.activity.ControlActivity;
import com.gardenguell.salad.ui.activity.VegetableActivity;
import com.gardenguell.salad.ui.activity.base.ToolbarActivity;
import com.gardenguell.salad.ui.adapter.ClickableRecyclerViewAdapter;
import com.gardenguell.salad.ui.adapter.DividerLineDecoration;
import com.gardenguell.salad.ui.adapter.UnitAdapter;
import com.gardenguell.salad.ui.view.MaterialDialog;
import com.gardenguell.salad.util.DisplayUtil;
import com.gardenguell.salad.util.ResUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by absurd on 16/2/10.
 */
public class UnitFragment extends BaseFragment{

    private RecyclerView mUnitList;

    private UnitAdapter mUnitAdapter;

    private BoxActivity mBoxActivity;

    private SaladClient mClient = new SaladClient();

    private CacheService cacheService = CacheService.getInstance(AppContext.getContext());

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case HandlerCenter.Message.REFRESH_UNIT_LIST:
                    refreshUnitList();
                    Toast.makeText(UnitFragment.this.getBaseActivity(), R.string.tip_refresh_unit_list, Toast.LENGTH_SHORT).show();
                    break;
                case HandlerCenter.Message.CLICK_WARNING:
                    final Unit u = (Unit)msg.obj;
                    int num = msg.arg1;
                    final MaterialDialog alert = new MaterialDialog(UnitFragment.this.getBaseActivity());
                    alert.setMessage("Unit" + num + "可以采摘了\n" + "建议在7天内完成采摘")
                            .setPositiveButton(R.string.ok, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    cacheService.messageDBManager.setRead(u.getInstanceId(), u.getVegetableId());
                                    mUnitAdapter.notifyChange();
                                    alert.dismiss();
                                }
                            }).show();

                    break;
                default:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_unit, container, false);
        HandlerCenter.getInstance().setHandler(HandlerCenter.Flag.UNIT_FRAGMENT, mHandler);
        // set the collor of the status bar and toolbar
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            getBaseActivity().getWindow().setStatusBarColor(ResUtil.getColor(R.color.green_color_primary));
        if(getBaseActivity() instanceof ToolbarActivity) {
            ((ToolbarActivity) getBaseActivity()).setToolbarColor(ResUtil.getColor(R.color.green_color_primary));
            ((ToolbarActivity)getBaseActivity()).hideToolbar();
        }

        mBoxActivity = ((BoxActivity)getBaseActivity());

        mUnitList = (RecyclerView)rootView.findViewById(R.id.unit_list);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getBaseActivity());
        mUnitList.setLayoutManager(layoutManager);
        // set every item's height is fixed
        mUnitList.setHasFixedSize(true);
        List<Unit> data = new ArrayList<>();
        mUnitAdapter = new UnitAdapter(data);
        mUnitAdapter.setOnRecyclerViewItemClickListener(new ClickableRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, BaseModel baseModel) {
                //TODO 这里为什么会返回-1?
                int position = mUnitAdapter.getItemIndex((Unit)baseModel);
                switch(view.getId()){
                    /**
                    case R.id.btn_unit_delete:
                        SaladClient client = new SaladClient();
                        client.finishVegetable(mBoxActivity.box.getMac(), position, getUsername(), new OnSuccessResponse() {
                            @Override
                            public void onSuccessWithNoBody() {
                                super.onSuccessWithNoBody();
                                HandlerCenter.getInstance().getHandler(HandlerCenter.Flag.UNIT_FRAGMENT)
                                        .sendEmptyMessage(HandlerCenter.Message.REFRESH_UNIT_LIST);
                            }
                        }, UnitFragment.this);
                        break;
                     **/
                    default:
                        if(((Unit)baseModel).getInstanceId().equals("000000000000000000000000")){
                            Intent intent = new Intent(mBoxActivity, VegetableActivity.class);
                            intent.putExtra("unitId", position);
                            intent.putExtra("mac", mBoxActivity.box.getMac());
                            startActivity(intent);
                        }else {
                            Intent intent = new Intent(mBoxActivity, ControlActivity.class);
                            intent.putExtra("unitId", position);
                            intent.putExtra("box", mBoxActivity.box);
                            intent.putExtra("unit", baseModel);
                            startActivity(intent);
                        }
                        break;
                }
            }
        });
        mUnitList.setAdapter(mUnitAdapter);
        DividerLineDecoration dividerLine = new DividerLineDecoration();
        dividerLine.setSize(DisplayUtil.dip2px(this.getBaseActivity(),10));
        dividerLine.setColor(ResUtil.getColor(R.color.main_background));
        mUnitList.addItemDecoration(dividerLine);
        refreshUnitList();
        return rootView;
    }

    private void refreshUnitList(){
        mClient.getUnitList(mBoxActivity.box.getMac(), getUsername(),
                new OnSuccessResponse<Unit>() {
                    @Override
                    public void onSuccessWithList(List<Unit> list) {
                        super.onSuccessWithList(list);
                        mUnitAdapter.setData(list);
                    }
                }, this);
    }



}


